import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../common/models/server_model.dart';
import '../../../common/services/server_service.dart';
import '../../../common/utils/index.dart';

class ServerMonitorController extends GetxController {
  final ServerService _serverService = Get.find<ServerService>();
  late final String serverId;
  
  Rx<ServerModel?> server = Rx<ServerModel?>(null);
  Rx<ServerStatusData?> statusData = Rx<ServerStatusData?>(null);
  
  RxBool isLoading = false.obs;
  RxString errorMessage = ''.obs;
  
  // 状态监听订阅
  StreamSubscription<ServerModel>? _stateSubscription;
  
  // 自动刷新定时器
  Timer? _refreshTimer;
  Timer? _countdownTimer; // 倒计时定时器
  RxInt refreshInterval = 5.obs; // 刷新间隔（秒）
  RxBool autoRefresh = true.obs; // 是否自动刷新
  RxInt nextRefreshIn = 0.obs; // 下次刷新倒计时（秒）

  @override
  void onInit() {
    super.onInit();
    debugPrint('🎬 ServerMonitorController: onInit');
    
    serverId = Get.parameters['id'] ?? '';
    debugPrint('   服务器ID: $serverId');
    
    if (serverId.isEmpty) {
      debugPrint('❌ ServerMonitorController: 服务器 ID 为空');
      LoadingUtil.error('服务器 ID 无效');
      Get.back();
      return;
    }
    
    _loadServer();
    _listenToServerStateChanges();
    _startAutoRefresh();
  }

  /// 监听服务器状态变化
  void _listenToServerStateChanges() {
    debugPrint('👂 ServerMonitorController: 开始监听服务器状态变化');
    _stateSubscription = _serverService.watchServer(serverId).listen((updatedServer) {
      debugPrint('📢 ServerMonitorController: 收到服务器状态更新 - ${updatedServer.name}');
      server.value = updatedServer;
    });
  }

  /// 加载服务器信息
  Future<void> _loadServer() async {
    debugPrint('📋 ServerMonitorController: 加载服务器信息 - ID: $serverId');
    
    server.value = _serverService.getServer(serverId);
    if (server.value == null) {
      debugPrint('❌ ServerMonitorController: 服务器不存在');
      LoadingUtil.error('服务器不存在');
      Get.back();
      return;
    }
    
    debugPrint('✅ ServerMonitorController: 服务器信息加载成功');
    
    // 检查是否已连接
    if (_serverService.isConnected(serverId)) {
      debugPrint('🔗 ServerMonitorController: 服务器已连接，获取监控数据');
      await fetchMonitoringData();
    } else {
      debugPrint('⚠️ ServerMonitorController: 服务器未连接');
      LoadingUtil.error('服务器未连接，请先连接服务器');
    }
  }

  /// 获取监控数据
  Future<void> fetchMonitoringData() async {
    if (!_serverService.isConnected(serverId)) {
      debugPrint('❌ ServerMonitorController: 服务器未连接');
      errorMessage.value = '服务器未连接';
      return;
    }
    
    isLoading.value = true;
    errorMessage.value = '';
    
    try {
      debugPrint('🔍 ServerMonitorController: 获取监控数据...');
      final data = await _serverService.getServerStatus(serverId);
      statusData.value = data;
      
      debugPrint('✅ ServerMonitorController: 监控数据获取成功');
      debugPrint('   CPU: ${data.cpuUsage.toStringAsFixed(1)}%');
      debugPrint('   内存: ${data.memoryUsage.toStringAsFixed(1)}%');
      debugPrint('   磁盘: ${data.diskUsage.toStringAsFixed(1)}%');
    } catch (e) {
      errorMessage.value = e.toString();
      debugPrint('❌ ServerMonitorController: 获取监控数据失败 - $e');
      
      // 尝试使用缓存数据
      statusData.value = _serverService.getCachedStatus(serverId);
    } finally {
      isLoading.value = false;
    }
  }

  /// 启动自动刷新
  void _startAutoRefresh() {
    if (autoRefresh.value) {
      _refreshTimer?.cancel();
      _countdownTimer?.cancel();
      
      // 初始化倒计时
      nextRefreshIn.value = refreshInterval.value;
      
      // 启动倒计时定时器（每秒更新）
      _countdownTimer = Timer.periodic(
        const Duration(seconds: 1),
        (timer) {
          if (!autoRefresh.value || !_serverService.isConnected(serverId)) {
            timer.cancel();
            return;
          }
          
          nextRefreshIn.value--;
          
          // 倒计时结束，执行刷新
          if (nextRefreshIn.value <= 0) {
            fetchMonitoringData();
            nextRefreshIn.value = refreshInterval.value; // 重置倒计时
          }
        },
      );
      
      debugPrint('⏰ ServerMonitorController: 启动自动刷新 - 间隔: ${refreshInterval.value}秒');
    }
  }

  /// 切换自动刷新
  void toggleAutoRefresh(bool value) {
    autoRefresh.value = value;
    debugPrint('🔄 ServerMonitorController: 自动刷新 ${value ? "开启" : "关闭"}');
    
    if (value) {
      _startAutoRefresh();
    } else {
      _refreshTimer?.cancel();
      _countdownTimer?.cancel();
      nextRefreshIn.value = 0;
    }
  }

  /// 设置刷新间隔
  void setRefreshInterval(int seconds) {
    refreshInterval.value = seconds;
    debugPrint('⏱️ ServerMonitorController: 刷新间隔设置为 ${seconds}秒');
    
    if (autoRefresh.value) {
      _startAutoRefresh();
    }
  }

  @override
  void onClose() {
    debugPrint('🔚 ServerMonitorController: onClose');
    _stateSubscription?.cancel();
    _refreshTimer?.cancel();
    _countdownTimer?.cancel();
    super.onClose();
  }
}

